﻿using System;
using System.IO;
using DeepZoomPivotConstructor.Utilities;
using System.ComponentModel.Composition;
using DeepZoomPivotConstructor.ErrorAndLoggingInterfaces;

namespace BuilderLibrary
{
    /// <summary>
    /// Builds a web site out of the results of the render. Does it "in place", and so expects
    /// a fairly specific directory structure. This is done so as not to have to recompile the
    /// output of the silverlight app.
    /// </summary>
    public class WebSiteBuilder
    {
        [Import]
        static IErrorLogger MyLogger { get; set; }

        /// <summary>
        /// Simple copy operation that copies files from the template over to the renderbase.
        /// This expects (!!!) that renderBase contains a subdir meeting, which contains meeting,
        /// which contains info.bin. If not, then nothing is going to be good!
        /// </summary>
        /// <param name="renderBase"></param>
        /// <returns></returns>
        public static FileInfo CreateWebSite(DirectoryInfo renderBase, string websiteTitle)
        {
            try
            {
                DirectoryInfo templateDir = new DirectoryInfo(ExternalToolLocations.LocationSLTemplateControl);
                CopyFiles(templateDir, renderBase, false,
                    f => f.Extension == ".jpg" || f.Extension == ".jpeg" || f.Extension == ".png" || f.Extension == ".xap" || f.Name == "AppManifest.xaml" || f.Name == "TestPage.html"
                    );
                ///CopyFiles(templateDir, renderBase);
                FileInfo testPage = new FileInfo(renderBase + @"\TestPage.html");
                FileInfo finalPage = new FileInfo(renderBase + @"\ViewConference.html");
                if (finalPage.Exists)
                {
                    finalPage.Delete();
                    finalPage.Refresh();
                }
                testPage.MoveTo(finalPage.FullName);
                finalPage.Refresh();
                finalPage.ReplaceText("<title>DeepTalkDisplay</title>", "<title>" + websiteTitle + "</title>");
                finalPage.InsertAsFirstLine("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
                return finalPage;
            }
            catch (Exception e)
            {
                MyLogger.LogMessage("Failed To Copy Over Website", e.Message, e.InnerException);
                throw;
            }
        }

        /// <summary>
        /// Copy files in dir to dest.
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="dest"></param>
        private static void CopyFiles(DirectoryInfo dir, DirectoryInfo dest, bool recusrive = true, Func<FileInfo, bool> checkBeforeCopy = null)
        {
            if (!dest.Exists)
            {
                dest.Create();
            }

            if (recusrive)
            {
                foreach (var d in dir.GetDirectories())
                {
                    CopyFiles(d, new DirectoryInfo(dest.FullName + "\\" + d.Name), recusrive, checkBeforeCopy);
                }
            }

            foreach (var f in dir.GetFiles())
            {
                FileInfo destFile = new FileInfo(dest.FullName + "\\" + f.Name);
                if (checkBeforeCopy == null || checkBeforeCopy(destFile))
                {
                    if (!destFile.Exists || f.LastWriteTime > destFile.LastWriteTime)
                    {
                        f.CopyTo(destFile.FullName, true);
                    }
                }
            }
        }

        /// <summary>
        /// Creates a link that will start the "local" web server to serve up the files so that
        /// a user can run things locally and view them in the browser.
        /// </summary>
        /// <param name="info"></param>
        public static FileInfo CreateLocalStart(DirectoryInfo baseBuildDir)
        {
            FileInfo shortcutFile = new FileInfo(baseBuildDir.FullName + "\\Conference Viewer.lnk");
            using (ShellLinkUtil.ShellLink link = new ShellLinkUtil.ShellLink())
            {
                link.Target = ExternalToolLocations.LocationWebViewer;
                link.Arguments = "\"" + baseBuildDir.FullName + "\"";
                link.WorkingDirectory = baseBuildDir.FullName;
                link.Description = "View a rendered conference by starting a local web server and web browser";
                link.DisplayMode = ShellLinkUtil.ShellLink.LinkDisplayMode.edmMinimized;

                link.Save(shortcutFile.FullName);
            }
            return shortcutFile;
        }
    }
}
